package com.atjg.autocat.main


import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.hardware.camera2.CameraManager
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.core.content.FileProvider
import com.atjg.autocat.R
import com.atjg.autocat.databinding.ActivitySettingBinding
import com.atjg.autocat.dialog.UpdateDialog
import com.atjg.autocat.utils.FileUtils
import com.atjg.autocat.viewModel.MainViewModel
import com.azhon.appupdate.config.UpdateConfiguration
import com.azhon.appupdate.listener.OnDownloadListener
import com.azhon.appupdate.manager.DownloadManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
import com.zhy.baselibrary.base.BaseActivity
import com.zhy.baselibrary.base.BaseData
import com.zhy.baselibrary.expand.ToastMgr
import com.zhy.baselibrary.utils.Klog
import com.zhy.baselibrary.utils.clickWithTrigger
import java.io.File


class SettingsActivity : BaseActivity<ActivitySettingBinding, MainViewModel>() {
    private var zkdkPort = "/dev/ttyS0"
    private var dkqdkPort = "/dev/ttyS1"
    private var shddkPort = "/dev/ttyS4"
    private var zkdkPosition = "0"
    private var dkqdkPosition = "1"
    private var shddkPosition = "4"
    private var url = "http://192.168.1.10/webcapture.jpg?command=snap&channel=0"
    private var hkUrl = "http://admin:jxn124578@192.168.1.10/ISAPI/Streaming/channels/101/picture"
    private var faceUsb = "-1"
    private var pzID2Position = "1"
    private var pzID1Position = "1"
    private var box1Usb = "0"
    private var box2Usb = "1"
    val zkdkList = listOf(
        "/dev/ttyS0",
        "/dev/ttyS1",
        "/dev/ttyS2",
        "/dev/ttyS3",
        "/dev/ttyS4",
        "/dev/ttyS5"
    )

    val dkqdkList = listOf(
        "/dev/ttyS0",
        "/dev/ttyS1",
        "/dev/ttyS2",
        "/dev/ttyS3",
        "/dev/ttyS4",
        "/dev/ttyS5"
    )
    val shddkList = listOf(
        "/dev/ttyS0",
        "/dev/ttyS1",
        "/dev/ttyS2",
        "/dev/ttyS3",
        "/dev/ttyS4",
        "/dev/ttyS5"
    )

    @SuppressLint("SetTextI18n")
    override fun initialize() {
        binding.ntbBar.ivLeftImageView.visibility = View.GONE
        val config = SPUtils.getInstance().getString("config")
        Klog.e("------config", config)
        setSalePort()
        setDKQPort()
        setSHJPort()
        initCamero()
        if (App.app1 == "1") {
            binding.cbsc.visibility = View.GONE
            binding.cbScan.visibility = View.GONE
            binding.cbFace.visibility = View.GONE
            binding.cbNet.visibility = View.GONE
        }

        if (!config.isNullOrEmpty()) {
            val configJson = Gson().fromJson(config, HashMap::class.java)
            val isPingBao = configJson["isPingBao"] ?: false
            val pingBaoTime = configJson["pingBaoTime"] ?: "30"
            binding.etPingBao.setText(pingBaoTime as String)
            val isDuKaQi = configJson["isDuKaQi"] ?: false
            val isAllNet = configJson["isAllNet"] ?: false

            val isXueHao = configJson["isXueHao"] ?: false
            val isWechat = configJson["isWechat"] ?: true
            val isPhone = configJson["isPhone"] ?: true
            val isZCH = configJson["isZCH"] ?: false
            val isSC = configJson["isSC"] ?: false
            val isScan = configJson["isScan"] ?: false
            val isFace = configJson["isFace"] ?: false
            val isGG = configJson["isGG"] ?: false
            val isFinger = configJson["isFinger"] ?: false
            val isFullScreen = configJson["isFullScreen"] ?: false
            val isRegist = configJson["isRegist"] ?: false
            val zkdkPort = configJson["zkdkPort"] ?: ""
            val dkqdkPort = configJson["dkqdkPort"] ?: ""
            val shddkPort = configJson["shddkPort"] ?: ""
            val zkdkPosition = configJson["zkdkPosition"] ?: "0"
            val dkqdkPosition = configJson["dkqdkPosition"] ?: "1"
            val shddkPosition = configJson["shddkPosition"] ?: "4"

            val url = configJson["url"] ?: ""
            val hkUrl = configJson["hkUrl"] ?: ""
            val isCBDef = configJson["isCBDef"] ?: true
            val isCBHK = configJson["isCBHK"] ?: false
            faceUsb = (configJson["faceUsb"] ?: "-1") as String
            when (faceUsb) {
                "1" -> {
                    binding.rbFaceUsb1.isChecked = true
                }
                "0" -> {
                    binding.rbFaceUsb0.isChecked = true
                }
                else -> {
                    binding.rbFaceFalse.isChecked = true
                }
            }
            box1Usb = (configJson["box1Usb"] ?: "0") as String
            box2Usb = (configJson["box2Usb"] ?: "1") as String
            when (box1Usb) {
                "-1" -> binding.rbBox1False.isChecked = true
                "0" -> binding.rbBox1Usb0.isChecked = true
                "1" -> binding.rbBox1Usb1.isChecked = true
            }
            when (box2Usb) {
                "-1" -> binding.rbBox2False.isChecked = true
                "0" -> binding.rbBox2Usb0.isChecked = true
                "1" -> binding.rbBox2Usb1.isChecked = true
            }
            binding.cbWetch.isChecked = isWechat as Boolean
            binding.cbXueHao.isChecked = isXueHao as Boolean
            binding.cbPhone.isChecked = isPhone as Boolean
            binding.cbDef.isChecked = isCBDef as Boolean
            binding.cbHK.isChecked = isCBHK as Boolean
            binding.etUrl.setText(url as String)
            binding.etHKUrl.setText(hkUrl as String)
            binding.cbPingBao.isChecked = isPingBao as Boolean
            binding.cbDuKaqi.isChecked = isDuKaQi as Boolean
            binding.cbzch.isChecked = isZCH as Boolean
            binding.cbsc.isChecked = isSC as Boolean
            binding.cbScan.isChecked = isScan as Boolean
            binding.cbFace.isChecked = isFace as Boolean
            binding.cbgg.isChecked = isGG as Boolean
            binding.cbFinger.isChecked = isFinger as Boolean
            binding.cbRegist.isChecked = isRegist as Boolean
            binding.cbFullScreen.isChecked = isFullScreen as Boolean
            binding.cbNet.isChecked = isAllNet as Boolean
            binding.zkdk.setSelection((zkdkPosition.toString()).toInt())
            binding.dkqdk.setSelection((dkqdkPosition.toString()).toInt())
            binding.shddk.setSelection((shddkPosition.toString()).toInt())
            binding.devInfo.text =
                "主控端口号：$zkdkPort\n读卡器端口号：$dkqdkPort\n售货端口：$shddkPort"
        }

    }

    override fun setListener() {
        super.setListener()
        binding.rgFace.setOnCheckedChangeListener({ group, checkedId ->
            when (checkedId) {
                R.id.rbFaceFalse -> {
                    faceUsb = "-1"
                }

                R.id.rbFaceUsb0 -> {
                    faceUsb = "0"
                }

                R.id.rbFaceUsb1 -> {
                    faceUsb = "1"
                }
            }
        }
        )
        binding.rgBox1.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rbBox1Usb0 -> {
                    box1Usb = "0"
                }

                R.id.rbBox1Usb1 -> {
                    box1Usb = "1"
                }

                R.id.rbBox1False -> {
                    box1Usb = "-1"
                }
            }
        }
        binding.rgBox2.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rbBox2Usb0 -> {
                    box2Usb = "0"
                }

                R.id.rbBox2Usb1 -> {
                    box2Usb = "1"
                }

                R.id.rbBox2False -> {
                    box2Usb = "-1"
                }
            }
        }
        binding.tvConfig.clickWithTrigger {
            ActivityUtils.startActivity(ConfigActivity::class.java)
            ActivityUtils.finishActivity(SettingsActivity::class.java)
        }
        binding.tvOut.clickWithTrigger {
            ActivityUtils.finishAllActivities()
        }
        binding.tvVersion.clickWithTrigger {
            model.queryVersion()
        }
        binding.btReset.clickWithTrigger {
            binding.etUrl.setText(url)
        }
        binding.btHKReset.clickWithTrigger {
            binding.etHKUrl.setText(hkUrl)
        }
        binding.tvSave.clickWithTrigger {
            if (zkdkPort.isEmpty()) {
                ToastMgr.show("请选择主控端口号")
                return@clickWithTrigger
            }
            if (dkqdkPort.isEmpty()) {
                ToastMgr.show("请选择读卡器端口号")
                return@clickWithTrigger
            }
            if (shddkPort.isEmpty()) {
                ToastMgr.show("请选择售货端口")
                return@clickWithTrigger
            }
            if (binding.etUrl.text.isNullOrEmpty()) {
                ToastMgr.show("请录入普通地址")
                return@clickWithTrigger
            }
            if (binding.etHKUrl.text.isNullOrEmpty()) {
                ToastMgr.show("请录入海康地址")
                return@clickWithTrigger
            }
            if (binding.cbDef.isChecked && binding.cbHK.isChecked) {
                ToastMgr.show("请选择普通或海康")
                return@clickWithTrigger
            }
            val isPingBao = binding.cbPingBao.isChecked
            SPUtils.getInstance().put("isPingBao", isPingBao)
            val isDuKaQi = binding.cbDuKaqi.isChecked
            val isZCH = binding.cbzch.isChecked
            val isSC = binding.cbsc.isChecked
            val isScan = binding.cbScan.isChecked
            val isFace = binding.cbFace.isChecked
            val isGG = binding.cbgg.isChecked
            val isFullScreen = binding.cbFullScreen.isChecked
            val isAllNet = binding.cbNet.isChecked
            val saveJson = HashMap<String, Any>()
            saveJson["isPingBao"] = isPingBao
            val isXueHao = binding.cbXueHao.isChecked
            val isWechat = binding.cbWetch.isChecked
            val isPhone = binding.cbPhone.isChecked
            val pingBaoTime = binding.etPingBao.text.toString()
            if (pingBaoTime.isEmpty()) {
                saveJson["pingBaoTime"] = "30"
            } else {
                saveJson["pingBaoTime"] = pingBaoTime
            }
            saveJson["isDuKaQi"] = isDuKaQi
            saveJson["isXueHao"] = isXueHao
            saveJson["isWechat"] = isWechat
            saveJson["isPhone"] = isPhone
            saveJson["isZCH"] = isZCH
            saveJson["isSC"] = isSC
            saveJson["isScan"] = isScan
            saveJson["isFace"] = isFace
            saveJson["isGG"] = isGG
            saveJson["isFullScreen"] = isFullScreen
            saveJson["isAllNet"] = isAllNet
            saveJson["zkdkPort"] = zkdkPort
            saveJson["dkqdkPort"] = dkqdkPort
            saveJson["shddkPort"] = shddkPort
            saveJson["zkdkPosition"] = zkdkPosition
            saveJson["dkqdkPosition"] = dkqdkPosition
            saveJson["shddkPosition"] = shddkPosition
            saveJson["pzID2Position"] = pzID2Position
            saveJson["pzID1Position"] = pzID1Position
            saveJson["isFinger"] = binding.cbFinger.isChecked
            saveJson["isRegist"] = binding.cbRegist.isChecked
            saveJson["url"] = binding.etUrl.text.toString()
            saveJson["hkUrl"] = binding.etHKUrl.text.toString()
            saveJson["isCBDef"] = binding.cbDef.isChecked
            saveJson["isCBHK"] = binding.cbHK.isChecked
            saveJson["box1Usb"] = box1Usb
            saveJson["box2Usb"] = box2Usb
            saveJson["faceUsb"] = faceUsb
            SPUtils.getInstance().put("config", Gson().toJson(saveJson))
            ToastMgr.show("保存成功")
        }
        binding.tvFinish.clickWithTrigger {
            ActivityUtils.finishActivity(this)
        }
        binding.cbScan.setOnCheckedChangeListener { buttonView, isChecked ->

        }
    }

    private fun setDKQPort() {
        val adapter: ArrayAdapter<String> =
            ArrayAdapter(this, android.R.layout.simple_spinner_item, dkqdkList)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.dkqdk.adapter = adapter
        binding.dkqdk.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View?,
                position: Int,
                id: Long
            ) {
                dkqdkPort = dkqdkList[position]
                dkqdkPosition = position.toString()
                binding.devInfo.text =
                    "主控端口号：$zkdkPort\n读卡器端口号：$dkqdkPort\n售货端口：$shddkPort"
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        }
    }

    private fun setSalePort() {
        val adapter: ArrayAdapter<String> =
            ArrayAdapter(this, android.R.layout.simple_spinner_item, zkdkList)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.zkdk.adapter = adapter
        binding.zkdk.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View?,
                position: Int,
                id: Long
            ) {
                Klog.d("-------position----$position--------")
                zkdkPort = zkdkList[position]
                zkdkPosition = position.toString()
                binding.devInfo.text =
                    "主控端口号：$zkdkPort\n读卡器端口号：$dkqdkPort\n售货端口：$shddkPort"
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        }
    }

    private fun setSHJPort() {

        val adapter: ArrayAdapter<String> =
            ArrayAdapter(this, android.R.layout.simple_spinner_item, shddkList)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.shddk.adapter = adapter
        binding.shddk.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View?,
                position: Int,
                id: Long
            ) {
                shddkPort = shddkList[position]
                shddkPosition = position.toString()
                binding.devInfo.text =
                    "主控端口号：$zkdkPort\n读卡器端口号：$dkqdkPort\n售货端口：$shddkPort"
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initCamero() {
        val mCameraManager = getSystemService(CAMERA_SERVICE) as CameraManager
        val cameraIdList = mCameraManager.cameraIdList
        binding.tvCameraNum.text = "相机数量：${cameraIdList.size}"
        binding.tvCamera.text = "找到的相机：${cameraIdList.joinToString(",")}"
    }

    override fun onTimeout() {
    }

    private fun showUpdateDialog(it: BaseData<Any>) {
        //isUpdate 是否更新  isForcedUp 是否强制更新
        val updata = UpdateDialog(this)
        updata.setContent(it.note ?: "有新版本需要下载，欢迎体验新版本")
        updata.setVersion(it.apkversion)
        if (it.force) {
            updata.hintClose()
        }
        updata.setCanceledOnTouchOutside(false)
        updata.setCancelable(false)
        updata.show()
        updata.setOnUpdataListener(object : UpdateDialog.OnUpdataListener {
            override fun upData() {
                upDataVersion(updata, it.apkurl, it.apkversion)
            }

            override fun upClose() {
                updata.dismiss()
            }
        })
    }

    private fun upDataVersion(dialog: UpdateDialog, apkUrl: String, version: String) {
        val manager: DownloadManager = DownloadManager.getInstance(this)
        manager.setApkName("lajifenlei$version.apk")
            .setDownloadPath(FileUtils.getSandboxCameraOutputPath(this))
            .setApkUrl(apkUrl)
            .setAuthorities("com.atjg.autocat")
            .setSmallIcon(R.mipmap.ic_launcher)
            .download()
        val updateConfiguration = UpdateConfiguration()
        updateConfiguration.isShowNotification = false
        updateConfiguration.isShowBgdToast = false
        updateConfiguration.setEnableLog(false)
        updateConfiguration.setJumpInstallPage(true)
        updateConfiguration.setForcedUpgrade(true)
        updateConfiguration.setOnDownloadListener(object : OnDownloadListener {
            override fun downloading(max: Int, progress: Int) {
                dialog.showProgress((progress.toDouble() / max.toDouble() * 100).toInt())
                if (100 == (progress.toDouble() / max.toDouble() * 100).toInt()) {
                    dialog.dismiss()
                }
            }

            override fun start() {

            }

            override fun done(apk: File?) {
                dialog.dismiss()
            }

            override fun cancel() {
                dialog.dismiss()
            }

            override fun error(e: java.lang.Exception?) {
                dialog.dismiss()
            }
        })
        manager.configuration = updateConfiguration
    }

    override fun setData() {
        super.setData()
        model.queryVersion.observe(this, {
            showUpdateDialog(it)
        })
    }
}